<?php

/* * ***************************************************************
  :: _image ::
  Image upload and manipulation class

  Version 1.1         (15 Nov 2011)

  Copyright MJDIGITAL В©2009-2011
  Written by Mark Jackson
  All rights reserved

  Changelog
  v1.1    Fixed newName on upload
  Fixed extension replacement on upload
  Fixed padToFit is turned off when oversize is set to true


  Thanks for bug fixes/notifications to:
  Yamez - muleofyamez at yahoo     (strict image type chcking)
  Chuck - at Toucan Media Group    (image quality calculation fix
  Frank - at Advanced Virtual     (located bugs with filename replace and oversize + requesting version numbers)

 *  *************************************************************** */

class Bluembo_Image_ImageResize extends Bluembo_Image_Image {

    // available properties (variables)    REDEFINE IN PAGE AS NEEDED
    // GENERIC - as in used by upload and resize functions
    public $newName        = '';            // new image name (without file extension)
    public $returnType     = 'fullpath';    // specify return type - fullpath | array | bool | blob
    public $safeRename     = 'false';       // rename the new file to remove unsafe characters and spaces
    public $duplicates     = 'o';           // u = make unique / o = overwrite / e = error / a = abort
    // UPLOAD FUNCTION
    public $uploadTo       = 'uploaded/';   // folder to upload to (relative to calling document)
    // RESIZE FUNCTION
    public $source_file    = '';            // source file to resize
    public $newWidth       = '';            // new image width - e.g. '200' = 200 pixels
    public $newHeight      = '';            // new image height - e.g. '200' = 200 pixels
    public $namePrefix     = '';            // prefix the resized file
    public $newPath        = '';            // path to save the new resized file
    public $aspectRatio    = 'true';        // keep the aspect ratio - true | false
    public $oversize       = 'false';       // resize to fill space - this can cause oversized images but will fill the frame created by w/h supplied - true | false
    public $padToFit       = 'false';       // pad the image with the pad colour to fit the new image dimensions - true | false
    public $upscale        = 'false';       // enlarge smaller images or not - true | false
    public $setPosition    = 'cc';          // set position of image within its canvas - e.g. 'cc' = center x center y OR 'tr' = top right
    public $padColour      = '#FFFFFF';     // set background padding colour - '#XXXXXX' or 'transparent' (transparent requires PNG type)
    public $padTransparent = 'true';        // if uploading a GIF or PNG then set background as transparent - this overrides $padColour
    public $newImgType     = '';            // force resized image to be jpg | gif | png | wbmp - leave blank to match source type
    public $imgQuality     = '80';          // image quality 1-100 (%)
    // array of all generated error messages
    public $errors         = array(
        'no-params' => '<strong>Error:</strong> Please specify a required parametrs.',
        'no-image' => '<strong>Error:</strong> Please specify a source image - declare: $mj_Image->source_file = "path_to_your_image_here.jpg";',
        'no-width' => '<strong>Error:</strong> Please specify a width for the new image - declare: $mj_Image->newWidth = 100;',
        'no-height' => '<strong>Error:</strong> Please specify a height for the new image - declare: $mj_Image->newheight = 100;',
        'image-exists' => '<strong>Error:</strong> The image you specified already exists',
        'upl-no-array' => '<strong>Error:</strong> It appears the form did not submit a valid file - please try again.',
        'upl-ini-max' => '<strong>Error:</strong> The file uploaded exceeds the filesize limit set on this server',
        'upl-maxsize' => '<strong>Error:</strong> The file uploaded exceeds the filesize limit set for this form',
        'upl-partial' => '<strong>Error:</strong> The file was only partially uploaded - please try again',
        'upl-no-file' => '<strong>Error:</strong> No file was submitted for upload',
        'upl-no-tmpDir' => '<strong>Error:</strong> The temporary upload directory is missing',
        'upl-cant-write' => '<strong>Error:</strong> Failed to write to the temporary folder - please check the permissions',
        'upl-ext' => '<strong>Error:</strong> The upload was stopped due to an invalid file extension',
        'upl-no-size' => '<strong>Error:</strong> The file submitted for upload had a filesize of zero or was corrupt',
        'upl-failed' => '<strong>Error:</strong> The upload failed - the file could not be moved to the target location - please check the permissions',
        'no-crop-width' => '<strong>Error:</strong> Please specify a crop width for the new image',
        'no-crop-height' => '<strong>Error:</strong> Please specify a crop height for the new image',
        'no-crop-x' => '<strong>Error:</strong> Please specify a crop x position for the new image',
        'no-crop-y' => '<strong>Error:</strong> Please specify a crop y position for the new image',
        'crop-ext' => '<strong>Error:</strong> The crop was stopped due to an invalid file extension',
    );

    #################################################
    #                     METHODS                    #
    #################################################
    // This function runs when this class is instantiated

    public function __construct()
    {
        //echo 'newImage Constructed';
    }

    private function hex2dec($_hex)
    {
        $_color = str_replace('#', '', $_hex);
        $_ret   = array(
            'r' => hexdec(substr($_color, 0, 2)),
            'g' => hexdec(substr($_color, 2, 2)),
            'b' => hexdec(substr($_color, 4, 2))
        );
        return $_ret;
    }

    public function cleanUp($str)
    {
        $str = stripslashes($str);
        $str = str_replace(array(' ', '.JPG', '.PNG', '.GIF'), array('_', '.jpg', '.png', '.gif'), $str);
        $str = preg_replace("/[^A-Za-z0-9_\-\.]/i", "", $str);
        return $str;
    }

    public function deleteUploaded()
    {
        if (file_exists($this->source_file)) unlink($this->source_file);
    }

    private function _getSourceImage()
    {
        if (empty($this->source_file) || !file_exists($this->source_file)) return $this->doDie($this->errors['no-image']);
        $image_info = getimagesize($this->source_file);

        // set source as resource
        switch ($image_info['mime']) {
            case 'image/gif':
                if (imagetypes() & IMG_GIF) { // not the same as IMAGETYPE
                    $src           = imagecreatefromgif($this->source_file);
                    $this->imgType = ($this->newImgType !== '') ? $this->newImgType : 'gif';
                } else {
                    $this->doDie($this->errors['crop-ext'] . ' - GIF images are not supported');
                }
                break;
            case 'image/jpeg':
                if (imagetypes() & IMG_JPG) {
                    $src           = imagecreatefromjpeg($this->source_file);
                    $this->imgType = ($this->newImgType !== '') ? $this->newImgType : 'jpg';
                } else {
                    $this->doDie($this->errors['crop-ext'] . ' - JPEG images are not supported');
                }
                break;
            case 'image/png':
                if (imagetypes() & IMG_PNG) {
                    $src           = imagecreatefrompng($this->source_file);
                    imagealphablending($src, true); // setting alpha blending on (we want to blend this image with the canvas)
                    imagesavealpha($src, true); // save alphablending setting
                    $this->imgType = ($this->newImgType !== '') ? $this->newImgType : 'png';
                } else {
                    $this->doDie($this->errors['crop-ext'] . ' - PNG images are not supported');
                }
                break;
            case 'image/wbmp':
                if (imagetypes() & IMG_WBMP) {
                    $src           = imagecreatefromwbmp($this->source_file);
                    $this->imgType = ($this->newImgType !== '') ? $this->newImgType : 'wbmp';
                } else {
                    $this->doDie($this->errors['crop-ext'] . ' - WBMP images are not supported');
                }
                break;
            default:
                $this->doDie($this->errors['crop-ext'] . ' - ' . $image_info['mime'] . ' files are not supported');
                break;
        }

        return $src;
    }

    private function _saveImage($image)
    {
        // get result filename
        if (empty($this->source_file)) return $this->doDie($this->errors['no-image']);
        $srcPath = (strstr($this->source_file, '/')) ? substr($this->source_file, 0, strrpos($this->source_file, '/') + 1) : '';
        $srcName = str_replace($srcPath, '', $this->source_file);

        $path = ($this->newPath != '') ? trim($this->newPath) : trim($srcPath);
        if (substr($path, strlen($path) - 1, strlen($path)) != '/') $path = $path . '/';
        if (!file_exists($path)) mkdir($path, 0777);  // if path doesn't exist then create it and chmod to 0777

        $imgNameOrig = ($this->newName != '') ? $this->newName : $srcName;
        $imgName     = (strstr($imgNameOrig, '.')) ? substr($imgNameOrig, 0, strrpos($imgNameOrig, '.')) . '.' . $this->imgType : $imgNameOrig . '.' . $this->imgType; // make sure it has the correct extension
        if ($this->safeRename == 'true') $imgName     = $this->cleanUp($imgName);  // rename file to safe filename

        $preFix = ($this->namePrefix != '') ? $this->namePrefix : '';

        // Handle duplicates
        if (file_exists($path . $preFix . $imgName)) {
            switch ($this->duplicates) {
                case 'o': break;
                case 'e': $this->doDie($this->errors['image-exists']);
                    exit;
                case 'a': return false;
                    break;
                default: // make unique
                    $im = (strstr($imgName, '.')) ? substr($imgName, 0, strrpos($imgName, '.')) : $imgName;
                    $i  = 1;
                    while (file_exists($path . $im . $i . '.' . $this->imgType)) {
                        $i++;
                    }
                    $imgName = $im . $i . '.' . $this->imgType;
            }
        }

        $fullName = $path . $preFix . $imgName;

        // output image
        if ($this->padColour == 'transparent') {
            switch ($this->imgType) {
                case 'gif': $newImg  = imagegif($image, $path . $preFix . $imgName);
                default:
                    $quality = (intval($this->imgQuality) > 90) ? 9 : round(intval($this->imgQuality) / 10);
                    //imagealphablending($canvas, false);
                    //imagesavealpha($canvas, true);
                    $newImg  = imagepng($image, $path . $preFix . $imgName, $quality);
            }
        } else {
            switch ($this->imgType) {
                case 'gif': $newImg  = imagejpeg($image, $path . $preFix . $imgName, $this->imgQuality);
                case 'png':
                    $quality = (intval($this->imgQuality) > 90) ? 9 : round(intval($this->imgQuality) / 10);
                    //imagealphablending($canvas, false);
                    //imagesavealpha($canvas, true);
                    $newImg  = imagepng($image, $path . $preFix . $imgName, $quality);
                case 'wbmp': $newImg  = imagewbmp($image, $path . $preFix . $imgName);
                default: $newImg  = imagejpeg($image, $path . $preFix . $imgName, $this->imgQuality);
            }
        }

        // Return image, array or blob if required
        switch (strtolower($this->returnType)) {
            case 'array':
                $_ar = array(
                    'image' => $imgName,
                    'prefix' => $preFix,
                    'path' => $path,
                    'height' => imagesy($image),
                    'width' => imagesx($image)
                );
                return $_ar;
                break;
            case 'fullpath':
                return (file_exists($fullName)) ? $fullName : false;
                break;
            case 'blob':
                if (file_exists($fullName)) {
                    $fo   = fopen($fullName, 'r');
                    $blob = mysql_real_escape_string(fread($fo, filesize($fullName)));
                    fclose($fo);
                    return $blob;
                    break;
                } else {
                    return false;
                    break;
                }
            default:
                return (file_exists($fullName)) ? true : false;
                break;
        }
    }

    public function resize()
    {
        // ERROR CAPTURE
        // make sure the new dimensions are numbers
        if (!is_int($this->newWidth)) $this->newWidth  = intval($this->newWidth);
        if (!is_int($this->newHeight)) $this->newHeight = intval($this->newHeight);
        if (!$this->newWidth) return $this->doDie($this->errors['no-crop-width']);
        if (!$this->newHeight) return $this->doDie($this->errors['no-crop-height']);

        // If oversize is used then turn off padToFit
        if ($this->oversize == 'true') {
            $this->padToFit = 'false';
        }

        // input image
        $src = $this->_getSourceImage();



        // Source dimensions
        $s_width  = imagesx($src);
        $s_height = imagesy($src);

        // canvas dimensions
        $c_width  = $this->newWidth;
        $c_height = $this->newHeight;

        // maintain the aspect ratio
        if ($this->aspectRatio == 'true') {
            if ($s_width > $s_height) {
                if ($this->oversize == 'true') { // resize to fill the frame - oversized images
                    $resize_pc      = ($this->newHeight / $s_height);
                    $this->newWidth = round($s_width * $resize_pc);
                } else {
                    $resize_pc = ($this->newWidth / $s_width);
                    // make sure the new dimensions fit into defined space
                    if (round($s_height * $resize_pc) <= $this->newHeight) {
                        $this->newHeight = round($s_height * $resize_pc);
                    } else {
                        $resize_pc      = ($this->newHeight / $s_height);
                        $this->newWidth = round($s_width * $resize_pc);
                    }
                }
            } else {
                if ($this->oversize == 'true') { // resize to fill the frame - oversized images
                    $resize_pc       = ($this->newWidth / $s_width);
                    $this->newHeight = round($s_height * $resize_pc);
                } else {
                    $resize_pc = ($this->newHeight / $s_height);
                    // make sure the new dimensions fit into defined space
                    if (round($s_width * $resize_pc) <= $this->newWidth) {
                        $this->newWidth = round($s_width * $resize_pc);
                    } else {
                        $resize_pc       = ($this->newWidth / $s_width);
                        $this->newHeight = round($s_height * $resize_pc);
                    }
                }
            }
        }

        if ($this->padToFit != 'true') { // if padding not required then set canvas size to new image size aspect
            $c_width  = $this->newWidth;
            $c_height = $this->newHeight;
        }

        if ($this->upscale != 'true') {
            // do not upscale image
            if (($s_width <= $this->newWidth) && ($s_height <= $this->newHeight)) {
                $this->newWidth  = $s_width;
                $this->newHeight = $s_height;
                $c_width         = $this->newWidth;
                $c_height        = $this->newHeight;
            }
        }


        // set the position of source in the canvas
        if ($this->padToFit == 'true') {
            // set positions
            $top    = $left   = 0;
            $right  = $c_width - $this->newWidth;
            $cenX   = ($c_width / 2) - ($this->newWidth / 2);
            $cenY   = ($c_height / 2) - ($this->newHeight / 2);
            $bottom = $c_height - $this->newHeight;
            switch (true) {
                case (strstr($this->setPosition, ',')): // pixel x,y entered
                    $dim   = explode($this->setPosition, ',');
                    $x     = intval(@$dim[0]);
                    $y     = intval(@$dim[1]);
                    $toPos = array('dx' => $x, 'dy' => $y, 'sx' => 0, 'sy' => 0);
                    break;
                case ($this->setPosition == 'tl'): // top left
                    $toPos = array('dx' => $left, 'dy' => $top, 'sx' => 0, 'sy' => 0);
                    break;
                case ($this->setPosition == 'tr'): // top right
                    $toPos = array('dx' => $right, 'dy' => $top, 'sx' => 0, 'sy' => 0);
                    break;
                case ($this->setPosition == 'tc'): // top centre
                    $toPos = array('dx' => $cenX, 'dy' => $top, 'sx' => 0, 'sy' => 0);
                    break;
                case ($this->setPosition == 'bl'): // bottom left
                    $toPos = array('dx' => $left, 'dy' => $bottom, 'sx' => 0, 'sy' => 0);
                    break;
                case ($this->setPosition == 'br'): // bottom right
                    $toPos = array('dx' => $right, 'dy' => $bottom, 'sx' => 0, 'sy' => 0);
                    break;
                case ($this->setPosition == 'bc'): // bottom centre
                    $toPos = array('dx' => $cenX, 'dy' => $bottom, 'sx' => 0, 'sy' => 0);
                    break;
                case ($this->setPosition == 'cl'): // centre left
                    $toPos = array('dx' => $left, 'dy' => $cenY, 'sx' => 0, 'sy' => 0);
                    break;
                case ($this->setPosition == 'cr'): // centre right
                    $toPos = array('dx' => $right, 'dy' => $cenY, 'sx' => 0, 'sy' => 0);
                    break;
                default: // centred horz + vert
                    $toPos = array('dx' => $cenX, 'dy' => $cenY, 'sx' => 0, 'sy' => 0);
                    break;
            }
        } else {
            $toPos = array('dx' => 0, 'dy' => 0, 'sx' => 0, 'sy' => 0);
        }

        // Create target image
        $canvas = imagecreatetruecolor($c_width, $c_height);

        // colour the canvas
        if ($this->padColour == 'transparent') {
            $trans_colour = imagecolorallocatealpha($canvas, 0, 0, 0, 127);
            imagefill($canvas, 0, 0, $trans_colour);
            imagealphablending($canvas, true);
            imagesavealpha($canvas, true);
        } else {
            $col   = $this->hex2dec($this->padColour);
            $bgCol = imagecolorallocate($canvas, $col['r'], $col['g'], $col['b']);
            imagefill($canvas, 0, 0, $bgCol);
        }

        // Copy image
        imagecopyresampled($canvas, $src, $toPos['dx'], $toPos['dy'], $toPos['sx'], $toPos['sy'], $this->newWidth, $this->newHeight, $s_width, $s_height);

        // save created image
        $result = $this->_saveImage($canvas);

        // clean up
        imagedestroy($src);
        imagedestroy($canvas);

        return $result;
    }

    public function upload($ar)
    {
        // ERROR CAPTURE
        if (!isset($ar['name'])) return $this->doDie($this->errors['upl-no-array']);
        if ($ar['error'] != 0) {
            switch ($ar['error']) {
                case 1: return $this->doDie($this->errors['upl-ini-max']);
                    break;
                case 2: return $this->doDie($this->errors['upl-maxsize']);
                    break;
                case 3: return $this->doDie($this->errors['upl-partial']);
                    break;
                case 4: return $this->doDie($this->errors['upl-no-file']);
                    break;
                case 6: return $this->doDie($this->errors['upl-no-tmpDir']);
                    break;
                case 7: return $this->doDie($this->errors['upl-cant-write']);
                    break;
                case 8: return $this->doDie($this->errors['upl-ext']);
                    break;
            }
        }
        if (!$ar['size']) return $this->doDie($this->errors['upl-no-size']);

        // create variables
        $img_name     = $ar['name'];
        $img_type     = $ar['type'];
        $img_tmp_name = $ar['tmp_name'];
        $img_error    = $ar['error'];
        $img_size     = $ar['size'];

        // original extension
        $ext = substr(strrchr($img_name, '.'), 1);

        // rename file to safe filename
        if ($this->safeRename == 'true') {
            $imgPath  = str_replace(basename($img_name), "", $img_name);
            $imgName  = ($this->newName != '') ? $this->newName : $img_name;
            $imgName  = $this->cleanUp(basename($imgName));
            $img_name = $imgPath . $imgName;
        }

        // ensure the extension is correct if the name has been altered
        if (strrchr($img_name, '.')) { // has extension
            $new_ext = substr(strrchr($img_name, '.'), 1);
            if ($new_ext != $ext) {
                $img_name = str_replace($new_ext, '', $img_name) . '.' . $ext; // use original extension
            }
        } else { // no extension
            $img_name = $img_name . '.' . $ext; // add in original
        }

        // set target path
        $target_path = $this->uploadTo . basename($img_name);

        // Handle duplicates
        if (file_exists($target_path)) {
            switch ($this->duplicates) {
                case 'o': break;
                case 'e': $this->doDie($this->errors['image-exists']);
                    exit;
                case 'a': return false;
                    break;
                default: // make unique
                    $im   = (strstr(basename($img_name), '.')) ? substr(basename($img_name), 0, strrpos(basename($img_name), '.')) : basename($img_name);
                    $ext  = str_replace($im, "", basename($img_name));
                    $path = $this->uploadTo;
                    $i    = 1;
                    while (file_exists($path . $im . $i . $ext)) {
                        $i++;
                    }
                    $imgName     = $im . $i . $ext;
                    $imgPath     = str_replace(basename($img_name), "", $img_name);
                    $img_name    = $imgPath . $imgName;
                    $target_path = $this->uploadTo . $imgName;
            }
        }

        // Make path writable // chmod file to 0777 if possible
        if (file_exists($target_path)) {
            @chmod($target_path, 0777);
        }

        // Do upload / move image to target path
        $getFileResult = copy($img_tmp_name, $target_path); // 2thiink: why not the move_uploaded_file()?
        if (!$getFileResult) {
            $this->doDie($this->errors['upl-failed']);
            exit;
        }

        // add uploaded file to $this->source_file for resize function quick access
        $this->source_file = $this->uploadTo . basename($img_name);

        // Return image, array or blob if required
        switch (strtolower($this->returnType)) {
            case 'array':
                $_ar = array(
                    'image' => basename($img_name),
                    'path' => $this->uploadTo,
                    'size' => $img_size
                );
                return $_ar;
                break;
            case 'fullpath':
                return (file_exists($target_path)) ? $target_path : false;
                break;
            case 'blob':
                if (file_exists($target_path)) {
                    $fo   = fopen($target_path, 'r');
                    $blob = mysql_real_escape_string(fread($fo, filesize($target_path)));
                    fclose($fo);
                    return $blob;
                    break;
                } else {
                    return false;
                    break;
                }
            default:
                return (file_exists($target_path)) ? true : false;
                break;
        }
    }

    public function crop($w = false, $h = false, $x = false, $y = false)
    {
        // ERROR CAPTURE
        // make sure the new dimensions are numbers
        if (!is_int($w) && !($w = intval($w))) return $this->doDie($this->errors['no-crop-width']);
        if (!is_int($h) && !($h = intval($h))) return $this->doDie($this->errors['no-crop-height']);
        if (!is_int($x) && !($x = intval($x))) return $this->doDie($this->errors['no-crop-x']);
        if (!is_int($y) && !($y = intval($y))) return $this->doDie($this->errors['no-crop-y']);

        if (!is_int($this->newWidth) && !($this->newWidth  = intval($this->newWidth))) return $this->doDie($this->errors['no-crop-width']);
        if (!is_int($this->newHeight) && !($this->newHeight = intval($this->newHeight))) return $this->doDie($this->errors['no-crop-height']);

        // input image
        $src_image = $this->_getSourceImage();

        // create target image
        $res_image = imagecreatetruecolor($this->newWidth, $this->newHeight);
        imagecopyresampled(
                $res_image, $src_image, // resource dst_im, resource src_im
                0, 0, $x, $y, // dstX, dstY, srcX, srcY
                $this->newWidth, $this->newHeight, $w, $h  // 250 dstW, 250 dstH, 1024 srcW, 1024 srcH
        );
        $result = $this->_saveImage($res_image);

        // clean up
        imagedestroy($src_image);
        imagedestroy($res_image);

        return $result;
    }

    public function autoCrop()
    {
        // ERROR CAPTURE
        // make sure the new dimensions are numbers
        if (!is_int($this->newWidth)) $this->newWidth  = intval($this->newWidth);
        if (!is_int($this->newHeight)) $this->newHeight = intval($this->newHeight);
        if (!$this->newWidth) return $this->doDie($this->errors['no-crop-width']);
        if (!$this->newHeight) return $this->doDie($this->errors['no-crop-height']);

        // input image
        $src_image = $this->_getSourceImage();

        $res_width  = $this->newWidth;
        $res_height = $this->newHeight;
        $src_width  = imagesx($src_image);
        $src_height = imagesy($src_image);
        if ($src_width / $src_height > $res_width / $res_height) {
            $res_y     = $src_y     = 0;
            $rw        = $res_width * ($src_height / $res_height);
            $src_x     = ($src_width - $rw) / 2;
            $res_x     = 0;
            $src_width = $rw;
        } else {
            $res_x      = $src_x      = 0;
            $rh         = $res_height * ($src_width / $res_width);
            $src_y      = ($src_height - $rh) / 2;
            $res_y      = 0;
            $src_height = $rh;
        }

        // create target image
        $res_image = imagecreatetruecolor($res_width, $res_height);
        imagecopyresampled(
                $res_image, $src_image, // resource dst_im, resource src_im
                $res_x, $res_y, $src_x, $src_y, // dstX, dstY, srcX, srcY
                $res_width, $res_height, $src_width, $src_height  // dstW, dstH, srcW, srcH
        );

        // save created image
        $result = $this->_saveImage($res_image);

        // clean up
        imagedestroy($src_image);
        imagedestroy($res_image);

        return $result;
    }

    public function rotateJpg($fileName, $direction)
    {
        if (empty($fileName) || (!file_exists($fileName))) return $this->doDie($this->errors['no-image']);
        if ('left' == $direction) $direction = 90; else if ('right' == $direction) $direction = -90; else return $this->doDie($this->errors['no-params']);

        $source  = imagecreatefromjpeg($fileName);
        $rotated = imagerotate($source, $direction, 0);
        $saved   = imagejpeg($rotated, $fileName, 90);
        return $saved;
    }

    #######################################################
    #
    #        EXTRA IMAGE METHODS
    #
    #######################################################

    public function getImageWidth($img)
    {
        if (file_exists($img)) {
            list($width, $height) = getimagesize($img);
            return $width;
        } else {
            return 0;
        }
    }

    public function getImageHeight($img)
    {
        if (file_exists($img)) {
            list($width, $height) = getimagesize($img);
            return $height;
        } else {
            return 0;
        }
    }

    public function getImageSize($img)
    {
        if (file_exists($img)) {
            list($width, $height) = getimagesize($img);
            return array('width' => $width, 'height' => $height);
        } else {
            return array('width' => 0, 'height' => 0);
        }
    }

    public function doDie($msg, $file = "", $line = "")
    {                     // doDie - calls a die function with custom error
        if (($file != '') && ($line != '')) {
            die('<h4>Error:</h4>' . $msg . '<br/><br/>' .
                    '<strong>File:</strong> ' . $file .
                    ' - <strong>on line:</strong> ' . $line .
                    '</body></html>');
        } else {
            die($msg);
        }
    }

    public function getPhotoFilePath($prefix, $path, $pid)
    {
        $abcdfghij = str_pad($pid, 9, '0', STR_PAD_LEFT);
        $abc       = substr($abcdfghij, 0, 3);
        $dfg       = substr($abcdfghij, 3, 3);
        $path      = str_replace(array('{abc}', '{dfg}'), array($abc, $dfg), $path);
        $pathFull = $prefix . $path;
        // create path if no exists
        if (!is_dir($pathFull)) {
            $dirs     = explode('/', $path);
            $pathFull = $prefix . '/';
            foreach ($dirs as $dir) {
                if (!empty($dir)) {
                    $pathFull .= $dir . '/';
                    if (!is_dir($pathFull)) {
                        if (!mkdir($pathFull) || !chmod($pathFull, 0777)) return false;
                    }
                }
            }
        }
        return $pathFull;
    }

}

// END OF CLASS
/*

  YOU CAN DELETE EVERYTHING FROM HERE ONWARDS (although you may want to keep a closing ?>)

  public $uploadTo        = 'uploaded/';
  public $source_file     = '';
  public $newWidth         = '';
  public $newHeight         = '';
  public $newName         = '';
  public $namePrefix         = '';
  public $newPath         = '';
  public $duplicates        = 'u'; // u = make unique / o = overwrite / e = error / a = abort
  public $safeRename        = 'true';
  public $aspectRatio     = 'true';
  public $padToFit         = 'true';
  public $upscale         = 'false';
  public $setPosition        = 'cc';
  public $padColour         = '#FFFFFF';
  public $padTransparent    = 'true'; // if uploading a GIF or PNG then set background as transparent - this overrides $padColour
  public $returnType        = 'fullPath';
 
if (isset($_FILES['image'])) {
    $myImage           = new _image;
    $myImage->uploadTo = 'testDir/';
    $res               = $myImage->upload($_FILES['image']);
    if ($res) {
        // RESIZE
        //$myImage->padColour = '#222222';
        $myImage->newWidth  = 400;
        $myImage->newHeight = 300;
        $i                  = $myImage->resize();
        echo $i;
    }
} else {

    <form action="" method="post" enctype="multipart/form-data" name="form1" id="form1">
        <p>
            <input type="file" name="image" id="image" />
        </p>
        <p>
            <input type="submit" name="button" id="button" value="Submit" />
        </p>
    </form>

  */
